//
//  NetRequestClass.m
//  dongfengTest
//
//  Created by wxt on 2021/3/22.
//

#import "NetRequestClass.h"

@implementation NetRequestClass
#pragma 监测网络的可链接性
+ (BOOL)netWorkReachabilityWithURLString:(NSString *)strUrl
{
    BOOL isExistenceNetwork ;
    
    Reachability* reachability=[Reachability reachabilityWithHostName:strUrl];
    switch([reachability currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            break;
    }
    
    return  isExistenceNetwork;
}


/***************************************
 在这做判断如果有dic里有errorCode
 调用errorBlock(dic)
 没有errorCode则调用block(dic
 ******************************/

#pragma --mark GET请求方式

+ (void)TokenAuthNetRequestGETWithRequestURL:(NSString *)requestURLString
                               WithParameter:(NSDictionary *)parameter
                        WithReturnValeuBlock:(ReturnValueBlock)block
                          WithErrorCodeBlock:(ErrorCodeBlock)errorBlock
                            WithFailureBlock:(FailureBlock)failureBlock
{
    
    Reachability* reachab=[Reachability reachabilityWithHostName:requestURLString];
    NetworkStatus sta =[reachab currentReachabilityStatus];
    if (sta==0) {
        [JRToast showWithText:@"当前网络连接异常" topOffset:kHeight*0.4 duration:3.0];
        failureBlock();
    }else
    {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        //不设置
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.securityPolicy.allowInvalidCertificates = YES;
        [manager.securityPolicy setValidatesDomainName:NO];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //请求超时设置
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 20.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
     
        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        
        
        [manager.requestSerializer setValue:[stand objectForKey:@"token"] forHTTPHeaderField:@"Authorization"];
        
        
        [manager.requestSerializer setValue:[IMSecurity getDeviceIdentifier] forHTTPHeaderField:@"requestKey"];
        NSString * timestr = [TKLTools getNomeTimeData];

        [manager.requestSerializer setValue:timestr forHTTPHeaderField:@"timestsmp"];
        [manager.requestSerializer setValue:@"login" forHTTPHeaderField:@"operationDesc"];
    
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json", nil];
      
        
        [manager GET:requestURLString parameters:parameter headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                    ;
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                    if (dic[@"errcode"]) {
                        
                        errorBlock(dic);
                        
                    } else  {
                        
                        block(dic);
                        
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                   NSLog(@"%@",error) ;
                }];
        
        
      
        
        
        
    }
    
    
    
}
+ (void)TokenAuthNetRequestGETWithRequestURL:(NSString *)requestURLString
                                  WithString:(NSString *)parameter
               WithReturnValeuBlock:(ReturnValueBlock)block
                 WithErrorCodeBlock:(ErrorCodeBlock)errorBlock
                            WithFailureBlock:(FailureBlock)failureBlock{
    
    
    Reachability* reachab=[Reachability reachabilityWithHostName:requestURLString];
    
    
  
//    NSLog(@"%@",requestURLString);
    
    
    requestURLString = [requestURLString stringByAppendingString:parameter];
    requestURLString = [requestURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    
//    NSLog(@"%@",requestURLString);
    NetworkStatus sta =[reachab currentReachabilityStatus];
    if (sta==0) {
        [JRToast showWithText:@"当前网络连接异常" topOffset:kHeight*0.4 duration:3.0];
        failureBlock();
    }else
    {
    
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        //不设置
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.securityPolicy.allowInvalidCertificates = YES;
        [manager.securityPolicy setValidatesDomainName:NO];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //请求超时设置
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 20.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json", @"text/plain", nil];
        
        
        [manager GET:requestURLString parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                    ;
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                    
                    if (dic[@"errcode"]) {
                        
                        errorBlock(dic);
                        
                    } else  {
                        
                        block(dic);
                        
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    errorBlock(error);
                    [ MBProgressHUD  showError:@"连接服务器出错" toView:[UIApplication sharedApplication].keyWindow];
                    NSLog(@"%@",error);
                  
                    
                }];
        
       
        
        
    }
    
    
    
    
    
}

+ (void)NetRequestGETWithRequestURL:(NSString *)requestURLString
                      WithParameter:(NSDictionary *)parameter
               WithReturnValeuBlock:(ReturnValueBlock)block
                 WithErrorCodeBlock:(ErrorCodeBlock)errorBlock
                   WithFailureBlock:(FailureBlock)failureBlock
{
    
    Reachability* reachab=[Reachability reachabilityWithHostName:requestURLString];
    NetworkStatus sta =[reachab currentReachabilityStatus];
    if (sta==0) {
        [JRToast showWithText:@"当前网络连接异常" topOffset:kHeight*0.4 duration:3.0];
        failureBlock();
    }else
    {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        //不设置
//        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//        manager.securityPolicy.allowInvalidCertificates = YES;
//        [manager.securityPolicy setValidatesDomainName:NO];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
        [manager.requestSerializer setValue:@"Basic TlNUQ0FQUDphbXR1V0d0SVFtSlZkMW8wWW04eU1VMTZVVlExZHowOQ==" forHTTPHeaderField:@"Authorization"];
//
        [manager.requestSerializer setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forHTTPHeaderField:@"requestKey"];
        NSString * timestr = [TKLTools getNomeTimeData];

        [manager.requestSerializer setValue:timestr forHTTPHeaderField:@"timestsmp"];
        [manager.requestSerializer setValue:@"login" forHTTPHeaderField:@"operationDesc"];
        
   
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json", @"text/plain",@"text/html", nil];
        
        
        [manager GET:requestURLString parameters:parameter headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                    ;
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
                    
                    if (dic[@"errcode"]) {
                        
                        errorBlock(dic);
                        
                    } else  {
                        
                        block(dic);
                        
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"%@",error);
                    [ MBProgressHUD  showError:@"连接服务器出错" toView:[UIApplication sharedApplication].keyWindow];
                }];
        
        
       
        
        
    }
    
    
    
}


#pragma --mark POST请求方式

+ (void)NetRequestPOSTWithRequestURL: (NSString *) requestURLString
                       WithParameter: (NSDictionary *) parameter
                WithReturnValeuBlock: (ReturnValueBlock) block
                  WithErrorCodeBlock: (ErrorCodeBlock) errorBlock
                    WithFailureBlock: (FailureBlock) failureBlock
{
    
    
    Reachability* reachab=[Reachability reachabilityWithHostName:requestURLString];
 
    NetworkStatus sta =[reachab currentReachabilityStatus];
    if (sta==0) {
        [JRToast showWithText:@"当前网络连接异常" topOffset:kHeight*0.4 duration:3.0];
        failureBlock();
    }else
    {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        //不设置
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.securityPolicy.allowInvalidCertificates = YES;
        [manager.securityPolicy setValidatesDomainName:NO];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //请求超时设置
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 20.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json", nil];
        
        [manager POST:requestURLString parameters:parameter headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            
            if (dic[@"errcode"]) {
                
                errorBlock(dic);
                
            } else  {
                
                block(dic);
                
            }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"%@",error);
                    [ MBProgressHUD  showError:@"连接服务器出错" toView:[UIApplication sharedApplication].keyWindow];
                }];
        
        
        
    }
    
    
}



#pragma --mark POST上传图片

//+ (void)NetRequestPOSTImageWithParameter: (NSDictionary *) parameter image: (UIImage *) image
//                     WithReturnValeuBlock: (ReturnValueBlock) block
//                       WithErrorCodeBlock: (ErrorCodeBlock) errorBlock
//                         WithFailureBlock: (FailureBlock) failureBlock
//{
//
//    Reachability* reachab=[Reachability reachabilityWithHostName:@""];
//    NetworkStatus sta =[reachab currentReachabilityStatus];
//    if (sta==0) {
//        [JRToast showWithText:@"当前网络连接异常" topOffset:kHeight*0.4 duration:3.0];
//        failureBlock();
//    }else
//    {
//
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
//        //不设置
//        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//        manager.securityPolicy.allowInvalidCertificates = YES;
//        [manager.securityPolicy setValidatesDomainName:NO];
//
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
//        //请求超时设置
//        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//        manager.requestSerializer.timeoutInterval = 20.f;
//        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json", nil];
//
//        [manager POST:@"" parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//
//
//            NSData *uploadImageData = [[image compressImageSize] compressImageQuality];
//
//            NSLog(@"ImageSize===========%d", (int)uploadImageData.length);
//
//
//            NSDateFormatter * formatter=[[NSDateFormatter alloc]init];
//            [formatter setDateFormat:@"YYYYMMddHHmmss"];
//            NSString * CurrentTime=[formatter stringFromDate:[NSDate date]];
//
//            [formData appendPartWithFileData:uploadImageData
//                                        name:@"file"
//                                    fileName:[NSString stringWithFormat:@"image_%@_%d.jpg", CurrentTime, arc4random() % 100]
//                                    mimeType:@"image/jpeg"];
//
//
//
//
//        } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//
//            if (dic[@"errcode"]) {
//
//                errorBlock(dic);
//
//            } else  {
//
//                block(dic);
//
//            }
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//            failureBlock();
//
//        }];
//
//    }
//
//
//}




#pragma mark  网络工作  https配置
+ (AFSecurityPolicy*)customSecurityPolicy

{
    
    // /先导入证书
    
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];//证书的路径
    
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    
    //    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    //    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    
    // 如果是需要验证自建证书，需要设置为YES
    
    //securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    
    //如置为NO，建议自己添加对应域名的校验逻辑。
    
    // securityPolicy.validatesDomainName = NO;
    AFSecurityPolicy *  securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:[[NSSet alloc] initWithObjects:certData, nil]];
    //    securityPolicy.allowInvalidCertificates = YES;
    //     securityPolicy.validatesDomainName = NO;
    
    // securityPolicy.pinnedCertificates = @[certData];
    
    
    //NSLog(@"data:%@",certData);
    
    return securityPolicy;
    
}


//+ (void)NotLoggedInNetRequestPOSTWithRequestURL:(NSString *)requestURLString
//                                WithType:(NSInteger)type
//                           WithParameter:(NSDictionary *)parameter
//                    WithReturnValeuBlock:(ReturnValueBlock)block
//                      WithErrorCodeBlock:(ErrorCodeBlock)errorBlock
//                        WithFailureBlock:(FailureBlock)failureBlock {
//
//
//    Reachability* reachab=[Reachability reachabilityWithHostName:requestURLString];
//    NetworkStatus sta =[reachab currentReachabilityStatus];
//    if (sta==0) {
////        [JRToast showWithText:@"当前网络连接异常" topOffset:SCREEN_HEIGHT*0.4 duration:3.0];
//        failureBlock();
//    }else
//    {
//
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
//        //不设置
//        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//        manager.securityPolicy.allowInvalidCertificates = YES;
//        [manager.securityPolicy setValidatesDomainName:NO];
//
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
//        //请求超时设置
//        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//        manager.requestSerializer.timeoutInterval = 20.f;
//        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//
//        [manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"x-nnw-client"];
//
//        // 默认Basic Auth
//        //对二进制数据进行base64编码
//        NSData *data =[@"azp97762544:JuWRc36wXVxUfyXq" dataUsingEncoding:NSUTF8StringEncoding];
//        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Basic %@",[data base64EncodedStringWithOptions:0]] forHTTPHeaderField:@"Authorization"];
//
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json", nil];
//
//
//        NSDictionary* newParameter = @{@"grant_type":@"client_credentials"};
//
//        [manager POST:kNot_Login_Get_Token_Api parameters:newParameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//
//            if (dic[@"error"]) {
//
////                [[CheckUserData shareInstance] HandelWithErrorCode:dic];
//
//                if (dic[@"error_description"]) {
//                    SHOW_TIP(dic[@"error_description"]);
//                }
//
//                errorBlock(dic);
//
//            } else  {
//
//                NSString *access_token = dic[@"access_token"];
//
//                [[NSUserDefaults standardUserDefaults] setObject:access_token forKey:@"access_token"];
//
//                [NetRequestClass TokenAuthNetRequestPOSTWithRequestURL:requestURLString WithType:type WithParameter:parameter WithReturnValeuBlock:block WithErrorCodeBlock:errorBlock WithFailureBlock:failureBlock];
//
//            }
//            /***************************************
//             在这做判断如果有dic里有errorCode
//             调用errorBlock(dic)
//             没有errorCode则调用block(dic
//             ******************************/
//
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//            failureBlock();
//
//            DDLog(@"-----%ld----", error.code);
//            DDLog(@"-----%@----", error);
//            DDLog(@"nserror --------%@",[error localizedDescription]);
//            SHOW_TIP([error localizedDescription]);
//
//
//        }];
//
//    }
//
//}




//+ (void)RefreshAccessTokenWithRequestURL:(NSString *)requestURLString
//                                WithType:(NSInteger)type
//                           WithParameter:(NSDictionary *)parameter
//                    WithReturnValeuBlock:(ReturnValueBlock)block
//                      WithErrorCodeBlock:(ErrorCodeBlock)errorBlock
//                        WithFailureBlock:(FailureBlock)failureBlock {
//
//
//    Reachability* reachab=[Reachability reachabilityWithHostName:requestURLString];
//    NetworkStatus sta =[reachab currentReachabilityStatus];
//    if (sta==0) {
//        [JRToast showWithText:@"当前网络连接异常" topOffset:SCREEN_HEIGHT*0.4 duration:3.0];
//        failureBlock();
//    }else
//    {
//
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
//        //不设置
//        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//        manager.securityPolicy.allowInvalidCertificates = YES;
//        [manager.securityPolicy setValidatesDomainName:NO];
//
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
//        //请求超时设置
//        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//        manager.requestSerializer.timeoutInterval = 20.f;
//        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//
//        [manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"x-nnw-client"];
//
//        // 默认Basic Auth
//        //对二进制数据进行base64编码
//        NSData *data =[@"azp97762544:JuWRc36wXVxUfyXq" dataUsingEncoding:NSUTF8StringEncoding];
//        [manager.requestSerializer setValue:[NSString stringWithFormat:@"Basic %@",[data base64EncodedStringWithOptions:0]] forHTTPHeaderField:@"Authorization"];
//
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json", nil];
//
//        NSDictionary* newParameter;
//
//        if ([[CheckUserData shareInstance] isLogin]) {
//
//            newParameter = @{@"grant_type":@"refresh_token",
//                                           @"refresh_token":REFRESH_TOKEN
//                                           };
//
//        } else {
//
//            newParameter = @{@"grant_type":@"client_credentials"};
//
//        }
//
//        [manager POST:kNot_Login_Get_Token_Api parameters:newParameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//
//
//            if (dic) {
//
//                NSString *access_token = dic[@"access_token"];
//                [[NSUserDefaults standardUserDefaults] setObject:access_token forKey:@"access_token"];
//
//                NSString *refresh_token = dic[@"refresh_token"];
//
//                if (refresh_token.length > 0) {
//                    [[NSUserDefaults standardUserDefaults] setObject:refresh_token forKey:@"refresh_token"];
//                }
//
//                [NetRequestClass TokenAuthNetRequestPOSTWithRequestURL:requestURLString WithType:type WithParameter:parameter WithReturnValeuBlock:block WithErrorCodeBlock:errorBlock WithFailureBlock:failureBlock];
//
//            }
//
//
//
//
//            /***************************************
//             在这做判断如果有dic里有errorCode
//             调用errorBlock(dic)
//             没有errorCode则调用block(dic
//             ******************************/
//
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//            NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"] ;
//
//            NSDictionary *errorDic;
//
//            if (data) {
//                errorDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//            }
//
////            DDLog(@"-----%ld----", error.code);
////            DDLog(@"-----%@----", error);
////            DDLog(@"nserror --------%@",[error localizedDescription]);
//
//            if ([errorDic[@"state"] integerValue] == 1001) {
//
//                failureBlock();
//
//                TOAST(@"登录已过期，请重新登录！");
//
//                [NetRequestClass exitLogin];
//
//            } else {
//
//                SHOW_TIP([error localizedDescription]);
//
//                failureBlock();
//
//            }
//
//
//        }];
//
//    }
//
//}



+ (void)TokenAuthNetRequestPOSTWithRequestURL:(NSString *)requestURLString
                                WithParameter:(NSDictionary *)parameter
                         WithReturnValeuBlock:(ReturnValueBlock)block
                           WithErrorCodeBlock:(ErrorCodeBlock)errorBlock
                             WithFailureBlock:(FailureBlock)failureBlock
{
    
    Reachability* reachab=[Reachability reachabilityWithHostName:requestURLString];
    NetworkStatus sta =[reachab currentReachabilityStatus];
    if (sta==0) {
        [JRToast showWithText:@"当前网络连接异常" topOffset:kHeight*0.4 duration:3.0];
        failureBlock();
    }else
    {
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        
        //不设置
        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        manager.securityPolicy.allowInvalidCertificates = YES;
        [manager.securityPolicy setValidatesDomainName:NO];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        //请求超时设置
        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        manager.requestSerializer.timeoutInterval = 20.f;
        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
    
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json",@"text/html", nil];
//        NSLog(@"%@",parameter);
        
        [manager POST:requestURLString parameters:parameter headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            
            if (dic[@"errcode"]) {
                
                errorBlock(dic);
                
            } else  {
                
                block(dic);
                
            };
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    ;
                }];
        
       
        
    }
    
    
}


//+ (void)NetRequestPOSTWithRequestURL:(NSString *)requestURLString
//                       WithParameter:(NSDictionary *)parameter
//                WithReturnValeuBlock:(ReturnValueBlock)block
//                  WithErrorCodeBlock:(ErrorCodeBlock)errorBlock
//                    WithFailureBlock:(FailureBlock)failureBlock
//{
//
//    Reachability* reachab=[Reachability reachabilityWithHostName:requestURLString];
//    NetworkStatus sta =[reachab currentReachabilityStatus];
//    if (sta==0) {
//        [JRToast showWithText:@"当前网络连接异常" topOffset:SCREEN_HEIGHT*0.4 duration:3.0];
//        failureBlock();
//    }else
//    {
//
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//
//        //调用配置ssl证书（双向认证）
//        // [manager setSecurityPolicy:[self customSecurityPolicy]];
//
//        //不设置
//        manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//        manager.securityPolicy.allowInvalidCertificates = YES;
//        [manager.securityPolicy setValidatesDomainName:NO];
//
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
//
//        //请求超时设置
//        [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
//        manager.requestSerializer.timeoutInterval = 20.f;
//        [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
//
//        [manager.requestSerializer setValue:@"2" forHTTPHeaderField:@"x-nnw-client"];
//
//
//        if ([requestURLString hasPrefix:@"https://nwsapi.nanniwan.com"] || [requestURLString hasPrefix:@"http://192.168.1.165"] ) {
//            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"multipart/form-data",@"application/json", nil];
//            //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json", @"text/javascript", nil];
//        } else {
//            [manager.requestSerializer setValue:FROM forHTTPHeaderField:@"from"];
//            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//            // [manager.requestSerializer setValue:VERSION_CODE forHTTPHeaderField:@"version_code"];
//            [manager.requestSerializer setValue:@"100" forHTTPHeaderField:@"version-code"];
//        }
//
//
//        //  DDLog(@"----header----%@",manager.requestSerializer.HTTPRequestHeaders);
//        NSInteger page=[[parameter objectForKey:@"page"] integerValue];
//        if (page>1) {
//
//        }else
//        {
//
//            if (parameter[@"search_type"]) {
//
//            }else
//            {
//                if ([[parameter allKeys] containsObject:@"NotNeedWaitingView"]) {
//
//                }else{
//                    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
//                    [SVProgressHUD setFont:[UIFont systemFontOfSize:15]];
//                    [SVProgressHUD setForegroundColor:UIColorFromRGB(0x777777)];
//
//
//                }
//            }
//
//        }
//
//        NSMutableDictionary* newParameter=[NSMutableDictionary dictionaryWithDictionary:parameter];
//
//        //公共部分字典
//        //DDLog(@"---%@-----%@",DEVICESN,UUID);
//
//        if (!([requestURLString hasPrefix:@"https://nwsapi.nanniwan.com"] || [requestURLString hasPrefix:@"http://192.168.1.165"])) {
//            NSMutableDictionary* commenDic=[NSMutableDictionary dictionaryWithDictionary:@{@"device_sn":DEVICESN,@"uuid":UUID}];
//            if (UNIONID) {
//                [commenDic setObject:UNIONID forKey:@"unionid"];
//            }
//
//            if (commenDic.count>0) {
//                [newParameter addEntriesFromDictionary:commenDic];
//            }
//        }
//
//        [manager POST:requestURLString parameters:newParameter success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//            //DDLog(@"---%@", dic);
//            if (dic[@"errcode"]) {
//                [[CheckUserData shareInstance] HandelWithErrorCode:dic];
//                errorBlock(dic);
//
//            } else  {
//                block(dic);
//
//            }
//            if (parameter[@"search_type"]) {
//
//            }else
//            {
//                dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, 0.4 * NSEC_PER_SEC);
//                dispatch_after(timer, dispatch_get_main_queue(), ^{
//                    //[SVProgressHUD dismiss];
//                });
//            }
//
//
//            /***************************************
//             在这做判断如果有dic里有errorCode
//             调用errorBlock(dic)
//             没有errorCode则调用block(dic
//             ******************************/
//
//        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//
//
//
//            //           #ifdef DEBUG
//            //             NSString* errResponse = @"错误信息:仅Debug模式展示\n";
//            //             errResponse = [errResponse stringByAppendingString:[[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding]];
//            //             TOAST(errResponse);
//            //           #else
//            //             //do sth.
//            //           #endif
//
//
//            failureBlock();
//
//            if (parameter[@"search_type"]) {
//
//            } else {
//                dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, 0.4 * NSEC_PER_SEC);
//                dispatch_after(timer, dispatch_get_main_queue(), ^{
//                    //  [SVProgressHUD dismiss];
//                });
//            }
//
//
//            DDLog(@"-----%ld----", error.code);
//            DDLog(@"-----%@----", error);
//
//            DDLog(@"nserror --------%@",[error localizedDescription]);
//            SHOW_TIP([error localizedDescription]);
//
//            //            //发送通知下次请求
//            //            [[NSNotificationCenter defaultCenter] postNotificationName:kTabBarClickRequestAgain object:nil];
//
//        }];
//
//
//
//    }
//
//}




//取消网络请求
+(void)cancelRequest
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.operationQueue cancelAllOperations];
}



#pragma mark - 退出登录
//+ (void)exitLogin {
//
//    [UMengRecordTool umengEventCountWithId:@"plantrec_quit_times"];
//
//    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"uid"];
//    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"azp_token"];
//    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"access_token"];
//    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"refresh_token"];
//
//    LoginViewController *loginvc = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
//    UINavigationController *nvc_login = [[UINavigationController alloc] initWithRootViewController:loginvc];
//    [UIApplication sharedApplication].keyWindow.rootViewController = nvc_login;
////    [CheckUserData goLoginVc];
//
//    [ShareSDK cancelAuthorize:SSDKPlatformTypeWechat];
//
//    NSMutableDictionary* dict=[NSMutableDictionary dictionaryWithContentsOfFile:FILE_PATH(@"LoginData.plist")];
//    [dict removeAllObjects];
//    [dict writeToFile:FILE_PATH(@"LoginData.plist") atomically:YES];
//
//    //删除极光推送别名
//    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
//        if (iResCode == 0) {
//            DDLog(@"删除成功！");
//        }
//    } seq:0];
//
//}


@end
